using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using DotNetNuke.Entities.Profile;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Localization;
using Fortunate.Web;

namespace Code5Systems.FormMaster.Business
{

	public partial class FormController
	{
		
#region Control Related Methods
		/// -----------------------------------------------------------------------------
		/// <summary>
		/// Retuns a FormControlInfo Object given an XmlElement Node.
		/// </summary>
		/// <param name="controlNode">The XmlElement Node for the Current Cell</param>
		/// <returns>FormControlInfo</returns>
		/// <remarks>
		/// If the Control has Validation, this Function is called recursivly to populate
		/// the Validators Colllection.
		/// </remarks>
		/// <history>
		/// 	[steve]	4/30/2005	Created
		/// </history>
		/// -----------------------------------------------------------------------------
		
		static public ControlType GetControlType(string typeName)
		{
			ControlType type = ControlType.None;
			
			switch (typeName)
			{
				case "CheckBox":
					type = ControlType.CheckBox;
					break;
				case "CheckBoxList":
					type = ControlType.CheckBoxList;
					break;
				case "DropDownList":
					type = ControlType.DropDownList;
					break;
				case "RadioButtonList":
					type = ControlType.RadioButtonList;
					break;
				case "RegularExpressionValidator":
					type = ControlType.RegularExpressionValidator;
					break;
				case "RequiredFieldValidator":
					type = ControlType.RequiredFieldValidator;
					break;
				case "TextBox":
					type = ControlType.TextBox;
					break;
				case "ListBox":
					type = ControlType.ListBox;
					break;
				case "CompareValidator":
					type = ControlType.CompareValidator;
					break;
				case "Label":
					type = ControlType.Label;
					break;
				case "FileUpload":
					type = ControlType.FileUpload;
					break;
				case "SubmitButton":
					type = ControlType.SubmitButton;
					break;
				case "HiddenField":
					type = ControlType.HiddenField;
					break;
				case "ChkListValidator":
					type = ControlType.ChkListValidator;
					break;
				case "HTMLEditor":
					type = ControlType.HTMLEditor;
					break;
			}
			
			return type;
			
		}
		
		
		public FormControlInfo GetFormControlInfo(XElement ctl)
		{
			FormControlInfo ctlInfo = default(FormControlInfo);
			XmlReader reader = default(XmlReader);
			
			try
			{
				reader = ctl.CreateReader();
				reader.MoveToContent();
				ctlInfo = Utility.XmlDeserialize<FormControlInfo>(reader.ReadOuterXml());
				if (string.IsNullOrEmpty(ctlInfo.Label))
				{
					string labelValue = String.Empty;
					if (ctl.AttributeExists("Label"))
					{
						labelValue = ctl.Attributes("Label").First().Value;
					}

					ctl.Add(new XElement("Label", labelValue));
					ctlInfo.Label = labelValue;
					
					this._saveSerializationFixups = true;
				}
				if (!ctl.AttributeExists("FieldName"))
				{
					ctlInfo.FieldName = Utility.GetValidDbFieldName(Utility.CleanInputAll(ctlInfo.Label));
					ctl.Add(new XAttribute("FieldName", ctlInfo.FieldName));
					this._saveSerializationFixups = true;
				}
				if (ctlInfo.Validators.Where(v => v.Type == ControlType.RequiredFieldValidator).Count() > 0)
				{
					if (ctlInfo.Required == false)
					{
						ctlInfo.Required = true;
						this._saveSerializationFixups = true;
					}
				}
			}
			catch
			{
				this._saveSerializationFixups = true;
				XAttribute xAttribute = default(XAttribute);
				PropertyInfo[] properties = typeof(FormControlInfo).GetProperties();
				
				foreach (PropertyInfo prop in properties)
				{
					switch (prop.Name)
					{
						case "Validators":
							IEnumerable<XElement> xValidators = ctl.Elements("Validators").Elements("Control");
							foreach (XElement item in xValidators)
							{
								if (item.Attributes("Type").First().Value == "RequiredFieldValidator")
								{
									ctl.Attributes("Required").First().Value = "true";
								}
								foreach (XAttribute tempLoopVar_xAttribute in item.Attributes())
								{
									xAttribute = tempLoopVar_xAttribute;
									if (xAttribute.Value.ToLower() == "true")
									{
										xAttribute.Value = "true";
									}
									else if (xAttribute.Value.ToLower() == "false")
									{
										xAttribute.Value = "false";
									}
									if (xAttribute.Name == "CookieExpires")
									{
										if (string.IsNullOrEmpty(xAttribute.Value))
										{
											xAttribute.Value = "0";
										}
									}
								}
							}
							break;
						case "ListItems":
							IEnumerable<XElement> xListItems = ctl.Elements().Descendants("ListItem").ToList();
							foreach (XElement item in xListItems)
							{
								foreach (XAttribute tempLoopVar_xAttribute in item.Attributes())
								{
									xAttribute = tempLoopVar_xAttribute;
									if (xAttribute.Value.ToLower() == "true")
									{
										xAttribute.Value = "true";
									}
									else if (xAttribute.Value.ToLower() == "false")
									{
										xAttribute.Value = "false";
									}
								}
							}
							break;
						case "Label":
							if (!ctl.ElementExists("Label"))
							{
								ctl.Add(new XElement("Label", ctl.Attributes("Label").First().Value));
							}
							break;
						case "FieldName":
							if (!ctl.AttributeExists("FieldName"))
							{
								ctl.Add(new XAttribute("FieldName", Utility.GetValidDbFieldName(Utility.CleanInputAll((string) (ctl.Attributes("Label").First().Value)))));
							}
							break;
						default:
							xAttribute = ctl.Attributes(prop.Name).FirstOrDefault();
							if (xAttribute != null)
							{
								switch (prop.PropertyType.Name)
								{
									case "Boolean":
										if (xAttribute.Value.ToLower() == "true")
										{
											xAttribute.Value = "true";
										}
										else
										{
											xAttribute.Value = "false";
										}
										break;
									case "Integer":
										break;
									case "Int32":
										if (string.IsNullOrEmpty(xAttribute.Value))
										{
											xAttribute.Value = "0";
										}
										break;
								}
							}
							break;
					}
				}
				
				reader = ctl.CreateReader();
				reader.MoveToContent();
				ctlInfo = Utility.XmlDeserialize<FormControlInfo>(reader.ReadOuterXml());
			}
			
			ctlInfo.Label = HttpContext.Current.Server.HtmlDecode(ctlInfo.Label);
			ctlInfo.Text = HttpContext.Current.Server.HtmlDecode(ctlInfo.Text);
			
			return ctlInfo;
			
		}
		
		/// -----------------------------------------------------------------------------
		/// <summary>
		/// Returns a WebControl of the Type specified in the FormControlInfo.Type
		/// Property.
		/// </summary>
		/// <param name="oFormControlInfo">The FormControlInfo Object for the Current Cell</param>
		/// <returns>System.Web.UI.WebControls.WebControl</returns>
		/// <remarks>
		/// </remarks>
		/// <history>
		/// 	[steve]	4/30/2005	Created
		/// </history>
		/// -----------------------------------------------------------------------------
		public Control GetFormControl(FormControlInfo oFormControlInfo, bool isDesignTime = false)
		{
			
			WebControl objWebControl = null;
			Control objControl = null;
			Table objTable = new Table();
			FormSettings objFormSettings = Utility.GetFormSettings(this._moduleId);
			
			switch (oFormControlInfo.Type)
			{
				
			case ControlType.TextBox:
				objWebControl = new TextBox();
				objWebControl.ID = oFormControlInfo.ID;
				objWebControl.Width = Unit.Empty;

				((TextBox) objWebControl).Text = oFormControlInfo.Text;
				
				if (!String.IsNullOrWhiteSpace(oFormControlInfo.Width))
				{
					if (oFormControlInfo.Width.EndsWith("%"))
					{
						objWebControl.Width = Unit.Percentage(double.Parse(oFormControlInfo.Width.Replace("%", "")));
					}
					else
					{
						objWebControl.Width = Unit.Pixel(int.Parse(oFormControlInfo.Width));
					}
				}
				
				if (oFormControlInfo.Height != string.Empty)
				{
					objWebControl.Height = Unit.Pixel(int.Parse(oFormControlInfo.Height));
				}
				else
				{
					objWebControl.Height = Unit.Empty;
				}
				
				if (oFormControlInfo.Columns != string.Empty)
				{
					((TextBox) objWebControl).Columns = int.Parse(oFormControlInfo.Columns);
				}
				
				objWebControl.CssClass = oFormControlInfo.CssClass;
				
				((TextBox) objWebControl).TextMode = oFormControlInfo.TextMode;
				
				if (oFormControlInfo.TextMode == TextBoxMode.MultiLine)
				{
					if (oFormControlInfo.Rows != string.Empty)
					{
						((TextBox) objWebControl).Rows = int.Parse(oFormControlInfo.Rows);
					}
				}
				
				if (oFormControlInfo.MaxLength != string.Empty)
				{
					((TextBox) objWebControl).MaxLength = int.Parse(oFormControlInfo.MaxLength);
				}
				
				if (oFormControlInfo.TabIndex != string.Empty)
				{
					objWebControl.TabIndex = short.Parse(oFormControlInfo.TabIndex);
				}
				break;
				
			case ControlType.CheckBox:
				objWebControl = new C5CheckBox();
				objWebControl.ID = oFormControlInfo.ID;
				((C5CheckBox) objWebControl).Text = oFormControlInfo.Text;
				((C5CheckBox) objWebControl).CssClass = oFormControlInfo.CssClass;
				
				if (oFormControlInfo.Checked)
				{
					((C5CheckBox) objWebControl).Checked = oFormControlInfo.Checked;
				}
				break;
				
			case ControlType.CheckBoxList:
				objWebControl = new C5CheckBoxList();
				objWebControl.ID = oFormControlInfo.ID;
				objWebControl.CssClass = oFormControlInfo.CssClass;

				if (String.IsNullOrWhiteSpace(oFormControlInfo.Width))
				{
					objWebControl.Width = Unit.Empty;
				}
				else if (oFormControlInfo.Width.EndsWith("%"))
				{
					double dblOut;
					if (double.TryParse(oFormControlInfo.Width.Replace("%", ""), out dblOut))
					{
						objWebControl.Width = Unit.Percentage(dblOut);
					}
				}
				else
				{
					objWebControl.Width = Unit.Pixel(int.Parse(oFormControlInfo.Width));
				}
				
				if (oFormControlInfo.Height != string.Empty)
				{
					objWebControl.Height = Unit.Pixel(int.Parse(oFormControlInfo.Height));
				}
				else
				{
					objWebControl.Height = Unit.Empty;
				}
				
				FillListItems((ListControl) objWebControl, oFormControlInfo);
				break;
				
				
			case ControlType.RadioButtonList:
				objWebControl = new C5RadioButtonList();
				objWebControl.ID = oFormControlInfo.ID;
				objWebControl.CssClass = oFormControlInfo.CssClass;
				
				if (oFormControlInfo.Width != string.Empty)
				{
					if (oFormControlInfo.Width.EndsWith("%"))
					{
						double dblOut;
						if (double.TryParse(oFormControlInfo.Width.Replace("%", ""), out dblOut))
						{
							objWebControl.Width = Unit.Percentage(dblOut);
						}
					}
					else
					{
						objWebControl.Width = Unit.Pixel(int.Parse(oFormControlInfo.Width));
					}
				}
				else
				{
					objWebControl.Width = Unit.Empty;
				}
				
				if (oFormControlInfo.Height != string.Empty)
				{
					objWebControl.Height = Unit.Pixel(int.Parse(oFormControlInfo.Height));
				}
				else
				{
					objWebControl.Height = Unit.Empty;
				}
				
				FillListItems((ListControl) objWebControl, oFormControlInfo);
				break;
				
			case ControlType.DropDownList:
				objWebControl = new DropDownList();
				objWebControl.ID = oFormControlInfo.ID;
				objWebControl.CssClass = oFormControlInfo.CssClass;
				
				FillListItems((ListControl) objWebControl, oFormControlInfo);
				
				if (oFormControlInfo.IsParentList)
				{
					((DropDownList) objWebControl).CausesValidation = true;
				}
				break;
				
			case ControlType.ListBox:
				objWebControl = new ListBox();
				objWebControl.ID = oFormControlInfo.ID;
				objWebControl.CssClass = oFormControlInfo.CssClass;
				
				FillListItems((ListControl) objWebControl, oFormControlInfo);
				break;
				
			case ControlType.RequiredFieldValidator:
				objWebControl = new RequiredFieldValidator();
				objWebControl.ID = oFormControlInfo.ID;
				objWebControl.CssClass = objFormSettings.UseFormErrorFormatting ? "c5sFormError" : oFormControlInfo.CssClass;
				objWebControl.ForeColor = System.Drawing.Color.Empty;
				((RequiredFieldValidator) objWebControl).EnableClientScript = true;
				((RequiredFieldValidator) objWebControl).ErrorMessage = oFormControlInfo.ErrorMessage;
				
				if ((!objFormSettings.SupressFieldValidationMessages) || isDesignTime)
				{
					((RequiredFieldValidator) objWebControl).Text = oFormControlInfo.ErrorMessage;
				}
				else
				{
					((RequiredFieldValidator) objWebControl).Text = objFormSettings.SuppressedFieldCharacter;
				}
				
				((RequiredFieldValidator) objWebControl).ControlToValidate = oFormControlInfo.ControlToValidate;
				((RequiredFieldValidator) objWebControl).Display = oFormControlInfo.Display;
				((RequiredFieldValidator) objWebControl).InitialValue = oFormControlInfo.InitialValue;
				break;
				
			case ControlType.RegularExpressionValidator:
				objWebControl = new RegularExpressionValidator();
				objWebControl.ID = oFormControlInfo.ID;
				objWebControl.CssClass = objFormSettings.UseFormErrorFormatting ? "c5sFormError" : oFormControlInfo.CssClass;
				objWebControl.ForeColor = System.Drawing.Color.Empty;
				((RegularExpressionValidator) objWebControl).EnableClientScript = true;
				((RegularExpressionValidator) objWebControl).ErrorMessage = oFormControlInfo.ErrorMessage;
				
				if ((!objFormSettings.SupressFieldValidationMessages) || isDesignTime)
				{
					((RegularExpressionValidator) objWebControl).Text = oFormControlInfo.ErrorMessage;
				}
				else
				{
					((RegularExpressionValidator) objWebControl).Text = objFormSettings.SuppressedFieldCharacter;
				}
				
				((RegularExpressionValidator) objWebControl).ControlToValidate = oFormControlInfo.ControlToValidate;
				((RegularExpressionValidator) objWebControl).Display = oFormControlInfo.Display;
				((RegularExpressionValidator) objWebControl).ValidationExpression = oFormControlInfo.ValidationExpression;
				break;
				
			case ControlType.CompareValidator:
				objWebControl = new CompareValidator();
				objWebControl.ID = oFormControlInfo.ID;
				objWebControl.CssClass = objFormSettings.UseFormErrorFormatting ? "c5sFormError" : oFormControlInfo.CssClass;
				objWebControl.ForeColor = System.Drawing.Color.Empty;
				((CompareValidator) objWebControl).EnableClientScript = true;
				((CompareValidator) objWebControl).ErrorMessage = oFormControlInfo.ErrorMessage;
				
				if ((!objFormSettings.SupressFieldValidationMessages) || isDesignTime)
				{
					((CompareValidator) objWebControl).Text = oFormControlInfo.ErrorMessage;
				}
				else
				{
					((CompareValidator) objWebControl).Text = objFormSettings.SuppressedFieldCharacter;
				}
				
				((CompareValidator) objWebControl).ControlToValidate = oFormControlInfo.ControlToValidate;
				((CompareValidator) objWebControl).Display = oFormControlInfo.Display;
				((CompareValidator) objWebControl).Operator = oFormControlInfo.Operator;
				((CompareValidator) objWebControl).Type = oFormControlInfo.ValDataType;
				((CompareValidator) objWebControl).ControlToCompare = oFormControlInfo.ControlToCompare;
				((CompareValidator) objWebControl).ValueToCompare = oFormControlInfo.ValueToCompare;
				break;
				
			case ControlType.ChkListValidator:
				objWebControl = new CheckBoxListRequiredFieldValidator();
				objWebControl.ID = oFormControlInfo.ID;
				objWebControl.CssClass = objFormSettings.UseFormErrorFormatting ? "c5sFormError" : oFormControlInfo.CssClass;
				objWebControl.ForeColor = System.Drawing.Color.Empty;
				((CheckBoxListRequiredFieldValidator) objWebControl).EnableClientScript = true;
				((CheckBoxListRequiredFieldValidator) objWebControl).ErrorMessage = oFormControlInfo.ErrorMessage;
				
				if ((!objFormSettings.SupressFieldValidationMessages) || isDesignTime)
				{
					((CheckBoxListRequiredFieldValidator) objWebControl).Text = oFormControlInfo.ErrorMessage;
				}
				else
				{
					((CheckBoxListRequiredFieldValidator) objWebControl).Text = objFormSettings.SuppressedFieldCharacter;
				}
				
				((CheckBoxListRequiredFieldValidator) objWebControl).ControlToValidate = oFormControlInfo.ControlToValidate;
				((CheckBoxListRequiredFieldValidator) objWebControl).Display = oFormControlInfo.Display;
				((CheckBoxListRequiredFieldValidator) objWebControl).MinimumCheckBoxesRequired = oFormControlInfo.MinChecked;
				((CheckBoxListRequiredFieldValidator) objWebControl).MaximumCheckBoxesAllowed = oFormControlInfo.MaxChecked;
				break;
				
			case ControlType.Label:
				objWebControl = new Label();
				objWebControl.ID = oFormControlInfo.ID;
				objWebControl.CssClass = oFormControlInfo.CssClass;
				objWebControl.ForeColor = System.Drawing.Color.Empty;
				
				((Label) objWebControl).Text = oFormControlInfo.Text;

				if (oFormControlInfo.Width.EndsWith("%"))
				{
					objWebControl.Width = Unit.Percentage(double.Parse(oFormControlInfo.Width.Replace("%", "")));
				}
				else if (oFormControlInfo.Width != string.Empty)
				{
					objWebControl.Width = Unit.Pixel(int.Parse(oFormControlInfo.Width));
				}
				else
				{
					objWebControl.Width = Unit.Empty;
				}
				
				if (oFormControlInfo.Height != string.Empty)
				{
					objWebControl.Height = Unit.Pixel(int.Parse(oFormControlInfo.Height));
				}
				else
				{
					objWebControl.Height = Unit.Empty;
				}
				
				objWebControl.CssClass = oFormControlInfo.CssClass;
				break;
				
			case ControlType.SubmitButton:
				switch (oFormControlInfo.ButtonType)
				{
					case Code5Systems.FormMaster.Business.ButtonType.Button:
						objWebControl = new Button();
						((Button) objWebControl).Text = oFormControlInfo.Label;
						((Button) objWebControl).ValidationGroup = this.FormInfo.ValidationGroup;
						break;

					case Code5Systems.FormMaster.Business.ButtonType.LinkButton:
						objWebControl = new LinkButton();
						((LinkButton) objWebControl).Text = oFormControlInfo.Label;
						((LinkButton)objWebControl).ValidationGroup = this.FormInfo.ValidationGroup;
						break;

					case Code5Systems.FormMaster.Business.ButtonType.ImageButton:
						objWebControl = new ImageButton();
						((ImageButton) objWebControl).ImageUrl = oFormControlInfo.ButtonImage;
						((ImageButton) objWebControl).AlternateText = oFormControlInfo.Label;
						((ImageButton)objWebControl).ValidationGroup = this.FormInfo.ValidationGroup;
						break;
						
				}
				
				objWebControl.ID = oFormControlInfo.ID;
				objWebControl.CssClass = oFormControlInfo.CssClass;
				objWebControl.ForeColor = System.Drawing.Color.Empty;
				break;
				
		}
		
		return ((Control) (objWebControl != null ? objWebControl : objControl));
		
	}
	
	private void FillListItems(ListControl control, FormControlInfo oFormControlInfo)
	{
		FMListItem item = default(FMListItem);
		
		if (oFormControlInfo.ListItems != null)
		{
			if (oFormControlInfo.IsChildList)
			{
				control.Items.Add(new ListItem(oFormControlInfo.PromptText, "0"));
			}
			foreach (FMListItem tempLoopVar_item in oFormControlInfo.ListItems)
			{
				item = tempLoopVar_item;
				if (oFormControlInfo.EncryptField)
				{
					if (item.Value != "0")
					{
						item.Value = Utility.EncryptString(item.Value);
					}
				}
				control.Items.Add(item.ListItem);
			}
		}
	}
	
	public string GetAutoFillValue(FormControlInfo objFormControlInfo)
	{
		string strFillValue = string.Empty;
		UserController objUserCtl = new UserController();
		UserInfo objUserInfo = default(UserInfo);
		objUserInfo = UserController.GetCurrentUserInfo();
		
		switch (objFormControlInfo.AutoFillType)
		{
			
		case AutoFillType.None:
			if (objFormControlInfo.Type == ControlType.TextBox 
				|| objFormControlInfo.Type == ControlType.HiddenField
				|| objFormControlInfo.Type == ControlType.CheckBox)
			{
				strFillValue = objFormControlInfo.Text;
			}
			break;
			
		case AutoFillType.Membership:
			
			if (objUserInfo != null)
			{
				
				switch (objFormControlInfo.AutoFillFrom)
				{
					case "FirstName":
						strFillValue = objUserInfo.FirstName;
						break;
						
					case "LastName":
						strFillValue = objUserInfo.LastName;
						break;
						
					case "FullName":
						strFillValue = objUserInfo.FirstName + " " + objUserInfo.LastName;
						break;
						
					case "DisplayName":
						strFillValue = objUserInfo.DisplayName;
						break;
						
					case "UserID":
						strFillValue = objUserInfo.UserID.ToString();
						break;
						
					case "Email":
						strFillValue = objUserInfo.Email;
						break;
						
					case "UserName":
						strFillValue = objUserInfo.Username;
						break;
						
					case "Cell":
						strFillValue = objUserInfo.Profile.Cell;
						break;
						
					case "City":
						strFillValue = objUserInfo.Profile.City;
						break;
						
					case "Country":
						strFillValue = objUserInfo.Profile.Country;
						break;
						
					case "Fax":
						strFillValue = objUserInfo.Profile.Fax;
						break;
						
					case "IM":
						strFillValue = objUserInfo.Profile.IM;
						break;
						
					case "PostalCode":
						strFillValue = objUserInfo.Profile.PostalCode;
						break;
						
					case "Region":
						strFillValue = objUserInfo.Profile.Region;
						break;
						
					case "Street":
						strFillValue = objUserInfo.Profile.Street;
						break;
						
					case "Telephone":
						strFillValue = objUserInfo.Profile.Telephone;
						break;
						
					case "Unit":
						strFillValue = objUserInfo.Profile.Unit;
						break;
						
					case "Website":
						strFillValue = objUserInfo.Profile.Website;
						break;
						
					default:
						strFillValue = objUserInfo.Profile.GetPropertyValue(objFormControlInfo.AutoFillFrom);
						break;
						
				}
			}
			break;
			
		case AutoFillType.Session:
			if (HttpContext.Current.Session[objFormControlInfo.AutoFillFrom] != null)
			{
				strFillValue = System.Convert.ToString(HttpContext.Current.Session[objFormControlInfo.AutoFillFrom]);
			}
			
			//TODO: Take this out when implementing Servicer Variables
			if (objFormControlInfo.AutoFillFrom == "[#REMOTE_ADDR#]")
			{
				strFillValue = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
			}
			if (objFormControlInfo.AutoFillFrom == "[#URL#]")
			{
				strFillValue = HttpContext.Current.Request.Url.AbsoluteUri;
			}
			break;
			
		case AutoFillType.Url:
			if (HttpContext.Current.Request.QueryString[objFormControlInfo.AutoFillFrom] != null)
			{
				strFillValue = System.Convert.ToString(HttpContext.Current.Request.QueryString[objFormControlInfo.AutoFillFrom]);
				
				//We will set this as a transient cookie and then check in the Else clause
				//This is handy for lead tracking should a user navigate from a Lead Form page
				//then comeback or even use another form setup to accept the same URL parameter
				//we can know how the user came to the site.
				Utility.SetCookie(objFormControlInfo.AutoFillFrom, strFillValue, DateTime.MinValue);
			}
			else
			{
				if (Utility.GetCookieValue(objFormControlInfo.AutoFillFrom) != null)
				{
					strFillValue = Utility.GetCookieValue(objFormControlInfo.AutoFillFrom);
				}
			}
			break;
		case AutoFillType.Cookie:
			if (Utility.GetCookieValue(objFormControlInfo.AutoFillFrom) != null)
			{
				strFillValue = Utility.GetCookieValue(objFormControlInfo.AutoFillFrom);
			}
			break;
			
		case AutoFillType.FormQuery:
			if (!string.IsNullOrEmpty(objFormControlInfo.AutoFillFrom) && !string.IsNullOrEmpty(FormInfo.FormQuery))
			{
				DataTable dt = this.GetQueryData(this._formInfo.ConnectionString, this._formInfo.FormQuery);
				if (dt != null)
				{
					if (dt.Rows.Count > 0)
					{
						if (dt.Columns[objFormControlInfo.AutoFillFrom] != null)
						{
							if (dt.Rows[0][objFormControlInfo.AutoFillFrom].GetType().ToString() != "System.DBNull")
							{
								strFillValue = (string) (dt.Rows[0][objFormControlInfo.AutoFillFrom].ToString());
							}
						}
					}
				}
			}
			break;
			
		case AutoFillType.FieldQuery:
			if (!string.IsNullOrEmpty(objFormControlInfo.AutoFillFrom) && !string.IsNullOrEmpty(objFormControlInfo.FieldQuery))
			{
				DataTable dt = this.GetQueryData(objFormControlInfo.ConnectionString, objFormControlInfo.FieldQuery);
				if (dt != null)
				{
					if (dt.Rows.Count > 0)
					{
						if (dt.Columns[objFormControlInfo.AutoFillFrom] != null)
						{
							if (dt.Rows[0][objFormControlInfo.AutoFillFrom].GetType().ToString() != "System.DBNull")
							{
								strFillValue = (string) (dt.Rows[0][objFormControlInfo.AutoFillFrom].ToString());
							}
						}
					}
				}
			}
			break;
			
		case AutoFillType.ServerVariables:
			if (HttpContext.Current.Request.ServerVariables[objFormControlInfo.AutoFillFrom] != null)
			{
				strFillValue = HttpContext.Current.Request.ServerVariables[objFormControlInfo.AutoFillFrom];
			}
			break;
	}
	
	if (strFillValue == null)
	{
		strFillValue = string.Empty;
	}
	
	if (objFormControlInfo.EncryptField)
	{
		switch (objFormControlInfo.Type)
		{
			case ControlType.CheckBoxList:
			case ControlType.DropDownList:
			case ControlType.ListBox:
			case ControlType.RadioButtonList:
				if (objFormControlInfo.ListItemToSave == ListItemToSave.Value)
				{
					strFillValue = Utility.EncryptString(strFillValue);
				}
				break;
			default:
				strFillValue = Utility.EncryptString(strFillValue);
				break;
				
		}
	}
	
	return strFillValue;
	
}

public void FillControlFromQuery(ListControl control, FormControlInfo controlInfo)
{
	bool bFillControl = true;
	DataTable dt = default(DataTable);
	string strText = default(string);
	string strValue = default(string);
	string strTextPart = default(string);
	string strValuePart = default(string);
	
	if (controlInfo.FieldQuery != string.Empty)
	{
		
		strTextPart = controlInfo.FillListItemText;
		strValuePart = strTextPart;
		
		if (controlInfo.FillListItemValue != string.Empty)
		{
			strValuePart = controlInfo.FillListItemValue;
		}
		
		string query = controlInfo.FieldQuery;
		
		if (controlInfo.IsChildList)
		{
			if (!string.IsNullOrEmpty(controlInfo.CascadingFieldQuery))
			{
				query = controlInfo.CascadingFieldQuery;
			}
		}
		
		dt = this.GetQueryData(controlInfo.ConnectionString, query);
		
		if (dt != null)
		{
			if (dt.Rows.Count > 0)
			{
				if (dt.Columns[strTextPart] == null)
				{
					control.Items.Add((dt.Rows[0][0]).ToString());
					bFillControl = false;
				}
				if (dt.Columns[strValuePart] == null && bFillControl)
				{
					control.Items.Add((dt.Rows[0][0]).ToString());
					bFillControl = false;
				}
				
				if (bFillControl)
				{
					foreach (DataRow row in dt.Rows)
					{
						if (row[strTextPart].GetType().ToString() != "System.DBNull")
						{
							if (row[strValuePart].GetType().ToString() != "System.DBNull")
							{
								strText = (row[strTextPart]).ToString();
								strValue = (row[strValuePart]).ToString();
								if (controlInfo.EncryptField && controlInfo.ListItemToSave == ListItemToSave.Value)
								{
									strValue = Utility.EncryptString(strValue);
								}
								control.Items.Add(new ListItem(strText, strValue));
							}
						}
					}
				}
				
			}
		}
	}
}

public ProfilePropertyDefinitionCollection GetProfileProperties()
{
	ProfilePropertyDefinitionCollection properties = ProfileController.GetPropertyDefinitionsByPortal(this._formInfo.PortalID);
	
	string strFirstName = Localization.GetString("MembershipFirst.Text", this._sharedResourceFile) + " ";
	strFirstName += Localization.GetString("MembershipName.Text", this._sharedResourceFile);
	
	string strLastName = Localization.GetString("MembershipLast.Text", this._sharedResourceFile) + " ";
	strLastName += Localization.GetString("MembershipName.Text", this._sharedResourceFile);
	
	ProfilePropertyDefinition firstNameProp = default(ProfilePropertyDefinition);
	ProfilePropertyDefinition LastNameProp = default(ProfilePropertyDefinition);
	ProfilePropertyDefinition emailProp = new ProfilePropertyDefinition();
	
	emailProp.PropertyCategory = Localization.GetString("MembershipContactInfo.Text", this._sharedResourceFile);
	emailProp.PropertyName = Localization.GetString("MembershipEmail.Text", this._sharedResourceFile);
	emailProp.PropertyValue = "Email";
	emailProp.ViewOrder = 24;
	properties.Add(emailProp);
	if (properties.GetByName(strFirstName.Replace(" ", "")) == null)
	{
		firstNameProp = new ProfilePropertyDefinition();
		firstNameProp.PropertyCategory = Localization.GetString("MembershipName.Text", this._sharedResourceFile);
		firstNameProp.PropertyName = strFirstName;
		firstNameProp.PropertyValue = "FirstName";
		properties.Add(firstNameProp);
	}
	
	if (properties.GetByName(strLastName.Replace(" ", "")) == null)
	{
		LastNameProp = new ProfilePropertyDefinition();
		LastNameProp.PropertyCategory = Localization.GetString("MembershipName.Text", this._sharedResourceFile);
		LastNameProp.PropertyName = strLastName;
		LastNameProp.PropertyValue = "LastName";
		properties.Add(LastNameProp);
	}
	
	properties.Sort();
	
	return properties;
	
}

//When a Field is added or updated make sure the field name is unique.
public void CheckDuplicateFieldName(XDocument xDoc, FormControlInfo oFormControlInfo)
{
	IEnumerable<XElement> xControls = default(IEnumerable<XElement>);
	string existId = string.Empty;
	string existName = string.Empty;
	
	foreach (FormPageInfo oPage in Pages)
	{
		xDoc = XDocument.Parse(oPage.PageData);
		xControls = xDoc.Root.Elements("Controls").Elements("Control");
		
		foreach (XElement xControl in xControls)
		{
			if (xControl.AttributeExists("ID"))
			{
				existId = (string) (xControl.Attributes("ID").First().Value);
			}
			
			if (xControl.AttributeExists("FieldName"))
			{
				existName = (string) (xControl.Attributes("FieldName").First().Value);
			}
			else if (xControl.AttributeExists("Label"))
			{
				existName = Utility.GetValidControlID((string) (xControl.Attributes("Label").First().Value));
			}
			
			if ((!string.IsNullOrEmpty(existId)) && (!string.IsNullOrEmpty(existName)))
			{
				if (existName.ToLower() == oFormControlInfo.FieldName.ToLower())
				{
					if (existId != oFormControlInfo.ID)
					{
						throw (new Exception(string.Format(Localization.GetString("DuplicateFieldError", Utility.GetSharedResourceFile()), oFormControlInfo.FieldName, oPage.ShortName)));
					}
				}
			}
		}
	}
	
}

/// -----------------------------------------------------------------------------
/// <summary>
/// Given a FormControlInfo Object, Updates the given XmlDocument for that Control
/// </summary>
/// <param name="defXmlDoc">The Current Working Form XmlDocument</param>
/// <param name="oFormControlInfo">The FormControlInfo Object for the Current Cell</param>
/// <remarks>
/// If it is a validator the XPath to the control is different. Not too elegant at this time.
/// </remarks>
/// <history>
/// 	[steve]	4/30/2005	Created
/// </history>
/// -----------------------------------------------------------------------------
public void UpdateControlValues(XDocument xDoc, FormControlInfo oFormControlInfo)
{
	XElement xControl = default(XElement);
	
	CheckDuplicateFieldName(xDoc, oFormControlInfo);
	
	switch (oFormControlInfo.Type)
	{
		case ControlType.ChkListValidator:
		case ControlType.CompareValidator:
		case ControlType.RegularExpressionValidator:
		case ControlType.RequiredFieldValidator:
			xControl = this.GetValidatorControlElement(this.GetControlElement(xDoc, oFormControlInfo.TableRow, oFormControlInfo.TableCol), oFormControlInfo.Type);
			break;
		default:
			xControl = this.GetControlElement(xDoc, oFormControlInfo.TableRow, oFormControlInfo.TableCol);
			break;
	}
	
	if (xControl != null)
	{
		string serialized = (string) (Utility.XmlSerialize<FormControlInfo>(oFormControlInfo));
		XElement xChanged = XElement.Parse(serialized);
		XElement xParent = xControl.Parent;
		xControl.Remove();
		xParent.Add(xChanged);
	}
}

/// -----------------------------------------------------------------------------
/// <summary>
/// Sets specific values during the Design Time process.
/// </summary>
/// <param name="defXmlDoc">The Current Working Form XmlDocument</param>
/// <param name="oFormControlInfo">The FormControlInfo Object for the Current Cell</param>
/// <remarks>
/// Durning the design process some changes require immediate updating to
/// enable the design time form to offer the correct inupt controls to the user.
/// </remarks>
/// <history>
/// 	[steve]	4/30/2005	Created
/// </history>
/// -----------------------------------------------------------------------------
public void UpdateTempControlValues(XDocument xDoc, FormControlInfo oFormControlInfo, ControlType type = ControlType.None)
{
	//Dim oControlNode As XmlNode
	XElement xControl = default(XElement);
	//Dim oNode As XmlNode
	XAttribute xAttr = default(XAttribute);
	XElement xElem = default(XElement);
	
	switch (oFormControlInfo.Type)
	{
		case ControlType.ChkListValidator:
		case ControlType.CompareValidator:
		case ControlType.RegularExpressionValidator:
		case ControlType.RequiredFieldValidator:
			xControl = this.GetValidatorControlElement(this.GetControlElement(xDoc, oFormControlInfo.TableRow, oFormControlInfo.TableCol), type);
			break;
		default:
			xControl = this.GetControlElement(xDoc, oFormControlInfo.TableRow, oFormControlInfo.TableCol);
			break;
	}
	
	if (xControl != null)
	{
		
		xAttr = xControl.Attribute("Type");
		if (xAttr != null)
		{
			xAttr.Value = oFormControlInfo.Type.ToString();
		}
		
		switch (oFormControlInfo.Type)
		{
			case ControlType.ChkListValidator:
			case ControlType.CompareValidator:
			case ControlType.RegularExpressionValidator:
			case ControlType.RequiredFieldValidator:
				return;
			default:
				xElem = xControl.Element("Label");
				if (xElem == null)
				{
					xControl.Add(new XElement("Label", new XCData(oFormControlInfo.Label)));
				}
				else
				{
					xElem.Value = string.Empty;
					xElem.Add(new XCData(oFormControlInfo.Label));
				}
				
				xAttr = xControl.Attribute("FieldName");
				if (xAttr == null)
				{
					xControl.Add(new XAttribute("FieldName", oFormControlInfo.FieldName));
				}
				else
				{
					xAttr.Value = oFormControlInfo.FieldName;
				}
				
				xAttr = xControl.Attribute("TextMode");
				if (xAttr != null)
				{
					xAttr.Value = oFormControlInfo.TextMode.ToString();
				}
				
				xAttr = xControl.Attribute("Required");
				if (oFormControlInfo.Required)
				{
					if (xAttr == null)
					{
						xControl.Add(new XAttribute("Required", "1"));
					}
					else
					{
						xAttr.Value = "1";
					}
				}
				else
				{
					if (xAttr != null)
					{
						xAttr.Remove();
					}
				}
				break;
		}
	}
}

/// -----------------------------------------------------------------------------
/// <summary>
/// Adds a new control to the Form
/// </summary>
/// <param name="defXmlDoc">The Current Working Form XmlDocument</param>
/// <param name="row">The Table Row to add the New Control</param>
/// <param name="col">The Table Column to add the New Control</param>
/// <returns>FormControlInfo</returns>
/// <remarks>
/// Retuns a new FormControlInfo Object with Default Values
/// The ID is based on a long DateTime string
/// </remarks>
/// <history>
/// 	[steve]	4/30/2005	Created
/// </history>
/// -----------------------------------------------------------------------------
public FormControlInfo AddControl(XDocument xDoc, ControlType type, string row, string col)
{
	FormControlInfo oFormControlInfo = null;
	string ctrlId = string.Empty;
	XElement xControls = default(XElement);
	
	oFormControlInfo = GetFormControlInfo(this.FormInfo, row, col);
	
	if (oFormControlInfo == null)
	{
		xControls = xDoc.Elements("Form").Elements("Controls").First();
		if (xControls != null)
		{
			ctrlId = "ctl_" + Guid.NewGuid().ToString().Replace("-", "");
			xControls.Add(new XElement("Control", new XAttribute("ID", ctrlId), new XAttribute("Type", type.ToString()), new XAttribute("FieldName", ""), new XAttribute("TableRow", row), new XAttribute("TableCol", col), new XAttribute("Required", "0"), new XAttribute("CssClass", "NormalTextBox"), new XAttribute("ColSpan", "1"), new XAttribute("RowSpan", "1"), new XAttribute("TabIndex", (type.ToString() == "Label") ? "0" : "1"), new XElement("Label", new XCData(""))));
			
			this.FormInfo.CurrentPage.PageData = xDoc.ToString();
			oFormControlInfo = GetFormControlInfo(ctrlId);
		}
	}
	
	return oFormControlInfo;
	
}


/// -----------------------------------------------------------------------------
/// <summary>
/// Delete Control at the specified Cell Location
/// </summary>
/// <param name="defXmlDoc">The Current Working Form XmlDocument</param>
/// <param name="row">The Table Row of the Control</param>
/// <param name="col">The Table Column of the Control</param>
/// <remarks>
/// </remarks>
/// <history>
/// 	[steve]	4/30/2005	Created
/// </history>
/// -----------------------------------------------------------------------------
public void DeleteControl(XDocument xDoc, string row, string col)
{
	XElement xControl = default(XElement);
	
	xControl = this.GetControlElement(xDoc, row, col);
	
	if (xControl != null)
	{
		xControl.Remove();
	}
}

/// -----------------------------------------------------------------------------
/// <summary>
/// Move a Control to the Specified Cell Location
/// </summary>
/// <param name="defXmlDoc">The Current Working Form XmlDocument</param>
/// <param name="row">The Target Row to move to</param>
/// <param name="col">The Target Column to move to</param>
/// <param name="moveDir">The direction to move</param>
/// <remarks>
/// </remarks>
/// <history>
/// 	[steve]	4/30/2005	Created
/// </history>
/// -----------------------------------------------------------------------------
public void MoveControl(XDocument xDoc, FormInfo oFormInfo, ControlLoaction oMoveSource, ControlLoaction oMoveTarget)
{
	XElement xControl = default(XElement);
	XElement xTargetControl = default(XElement);
	XAttribute xFormPage = default(XAttribute);
	XAttribute xTableRow = default(XAttribute);
	XAttribute xTableCol = default(XAttribute);
	string sourceCalcId;
	string targetCalcId;
	int sourcePage;

	//Get the Control at current location
	xControl = this.GetControlElement(xDoc, oMoveSource.Row.ToString(), oMoveSource.Col.ToString());
	
	if (xControl != null)
	{
		int col;
		if (int.TryParse(oMoveSource.Col.ToString(), out col))
		{
			col += 64;
		}

		sourceCalcId = String.Format("${0}{1}{2}", (char)col, xControl.Attribute("Page").Value, oMoveSource.Row.ToString());
		int.TryParse(xControl.Attribute("Page").Value, out sourcePage);

		if (int.TryParse(oMoveTarget.Col.ToString(), out col))
		{
			col += 64;
		}

		targetCalcId = String.Format("${0}{1}{2}", (char)col, xControl.Attribute("Page").Value, oMoveTarget.Row.ToString());

		FormPageInfo targetPage = (from p in this.Pages
								   where p.PageNum == oMoveTarget.Page
								   select p).FirstOrDefault();
		XDocument xTargetDoc = XDocument.Parse(targetPage.PageData);


		//Check to see if there is already a control in the target location
		xTargetControl = this.GetControlElement(xTargetDoc, oMoveTarget.Row.ToString(), oMoveTarget.Col.ToString());
		
		if (xTargetControl == null)
		{
			// Get the page of the current control
			xFormPage = xControl.Attribute("Page");

			if (xFormPage != null)
			{
				//Get the Row specified in the control to be moved
				xTableRow = xControl.Attribute("TableRow");
				if (xTableRow != null)
				{
					//Get the Col specified in the control to be moved
					xTableCol = xControl.Attribute("TableCol");
					if (xTableCol != null)
					{
						//Change the ColSpan and RowSpan to default 1 before moving the control
						XAttribute xTargetColSpam = xControl.Attribute("ColSpan");
						if (xTargetColSpam == null)
						{
							xControl.Add(new XAttribute("ColSpan", "1"));
						}
						else
						{
							xTargetColSpam.Value = "1";
						}

						//Change the RowSpan and RowSpan to default 1 before moving the control
						XAttribute xTargetRowSpan = xControl.Attribute("RowSpan");
						if (xTargetRowSpan == null)
						{
							xControl.Add(new XAttribute("RowSpan", "1"));
						}
						else
						{
							xTargetRowSpan.Value = "1";
						}

						// Change the page 
						xFormPage.Value = oMoveTarget.Page.ToString();
						xTableRow.Value = oMoveTarget.Row.ToString();
						xTableCol.Value = oMoveTarget.Col.ToString();

						SetValidatorControlsPosition(xControl, oMoveTarget);

						if (oMoveSource.Page != oMoveTarget.Page)
						{
							xControl.Remove();
							xTargetDoc.Element("Form").Element("Controls").Add(xControl);
							targetPage.PageData = xTargetDoc.ToString();
						}

						FormPageController pgCtrlr = new FormPageController();
						pgCtrlr.UpdateFormPage(targetPage);

						//Check all formulas on all pages to replace the CalcId
						foreach (var page in this.Pages)
						{
							XDocument xPage = XDocument.Parse(page.PageData);
							foreach (XElement control in xPage.Root.XPathSelectElements("//Controls/Control"))
							{
								XElement xFormula = control.Element("Formula");
								if (xFormula.Value.Contains(sourceCalcId))
								{
									xFormula.Value = xFormula.Value.Replace(sourceCalcId, targetCalcId);

									if (page.PageNum == oFormInfo.CurrentPage.PageNum)
									{
										XElement xFormulaCtrl = (from x in xDoc.Root.Element("Controls").Elements("Control")
																 where x.Attribute("ID").Value == control.Attribute("ID").Value
																 select x).FirstOrDefault();
										if (xFormulaCtrl != null)
										{
											xFormulaCtrl.Element("Formula").Value = xFormula.Value;
										}
									}
								}
							}
							page.PageData = xPage.ToString();
							pgCtrlr.UpdateFormPage(page);
						}
					}
				} 
			}
		}
	}
}

public void CopyControl(XDocument xDoc, FormInfo oFormInfo, ControlLoaction oCopySource, ControlLoaction oCopyTarget)
{
	FormControlInfo oTargetInfo = this.GetFormControlInfo(oFormInfo, oCopySource.Row.ToString(), oCopySource.Col.ToString());
	if (oTargetInfo != null)
	{
		FormPageInfo targetPage = (from p in this.Pages
								   where p.PageNum == oCopyTarget.Page
								   select p).FirstOrDefault();
		XDocument xTargetDoc = XDocument.Parse(targetPage.PageData);

		oTargetInfo.Page = oCopyTarget.Page;
		oTargetInfo.TableRow = (oCopyTarget.Row).ToString();
		oTargetInfo.TableCol = (oCopyTarget.Col).ToString();
		oTargetInfo.ColSpan = "1";
		oTargetInfo.RowSpan = "1";
		oTargetInfo.ID = "ctl_" + Guid.NewGuid().ToString().Replace("-", "");
		oTargetInfo.FieldName += DateTime.Now.Ticks;
		oTargetInfo.CascadingList = false;
		oTargetInfo.IsParentList = false;
		oTargetInfo.IsChildList = false;
		oTargetInfo.ParentControlID = string.Empty;
		oTargetInfo.ChildControlID = string.Empty;
		oTargetInfo.ChildControlName = string.Empty;
		oTargetInfo.PromptText = string.Empty;
		oTargetInfo.NotFoundText = string.Empty;
		
		foreach (FormControlInfo validator in oTargetInfo.Validators)
		{
			validator.ControlToValidate = oTargetInfo.ID;
			validator.Page = oCopyTarget.Page;
			validator.TableRow = oTargetInfo.TableRow;
			validator.TableCol = oTargetInfo.TableCol;
			switch (validator.Type)
			{
				case ControlType.RequiredFieldValidator:
					validator.ID = "rfv_" + Guid.NewGuid().ToString().Replace("-", "");
					break;
				case ControlType.RegularExpressionValidator:
					validator.ID = "rev_" + Guid.NewGuid().ToString().Replace("-", "");
					break;
				case ControlType.CompareValidator:
					validator.ID = "cv_" + Guid.NewGuid().ToString().Replace("-", "");
					break;
				case ControlType.ChkListValidator:
					validator.ID = "clv_" + Guid.NewGuid().ToString().Replace("-", "");
					break;
			}
		}
		
		string strSourceXml = (string) (Utility.XmlSerialize<FormControlInfo>(oTargetInfo));
		XElement xCopyElement = default(XElement);
		xCopyElement = XElement.Parse(strSourceXml);
		
		if (oFormInfo.CurrentPage.PageNum == targetPage.PageNum)
		{
			xDoc.Element("Form").Element("Controls").Add(xCopyElement);
			targetPage.PageData = xDoc.ToString();
		}
		else
		{
			xTargetDoc.Element("Form").Element("Controls").Add(xCopyElement);
			targetPage.PageData = xTargetDoc.ToString();
		}

		FormPageController pgCtrlr = new FormPageController();
		pgCtrlr.UpdateFormPage(targetPage);
	}
}

public void UpdateColSpan(XDocument xDoc, string row, string col, string colSpan)
{
	//Dim oControlNode As XmlNode
	XElement xControl = default(XElement);
	//Dim oColSpanNode As XmlNode
	XAttribute xColSpan = default(XAttribute);
	
	//oControlNode = defXmlDoc.SelectSingleNode("//Controls/Control[@TableRow=" & row & "][@TableCol=" & col & "]")
	xControl = this.GetControlElement(xDoc, row, col);
	if (xControl != null)
	{
		//oColSpanNode = oControlNode.SelectSingleNode("@ColSpan")
		xColSpan = xControl.Attribute("ColSpan");
		if (xColSpan == null)
		{
			xControl.Add(new XAttribute("ColSpan", colSpan));
			//Utility.AddAttribute(defXmlDoc, oControlNode, "ColSpan", colSpan)
		}
		else
		{
			xColSpan.Value = colSpan;
		}
	}
}

public void UpdateRowSpan(XDocument xDoc, string row, string col, string rowSpan)
{
	//Dim oControlNode As XmlNode
	XElement xControl = default(XElement);
	//Dim oColSpanNode As XmlNode
	XAttribute xRowSpan = default(XAttribute);
	
	//oControlNode = defXmlDoc.SelectSingleNode("//Controls/Control[@TableRow=" & row & "][@TableCol=" & col & "]")
	xControl = this.GetControlElement(xDoc, row, col);
	if (xControl != null)
	{
		//oColSpanNode = oControlNode.SelectSingleNode("@RowSpan")
		xRowSpan = xControl.Attribute("RowSpan");
		if (xRowSpan == null)
		{
			xControl.Add(new XAttribute("RowSpan", rowSpan));
			//Utility.AddAttribute(defXmlDoc, oControlNode, "RowSpan", rowSpan)
		}
		else
		{
			xRowSpan.Value = rowSpan;
		}
	}
}

public void UpdateTabIndex(XDocument xDoc, string row, string col, string tabIndex)
{
	//Dim oControlNode As XmlNode
	XElement xControl = default(XElement);
	//Dim oTabIndexNode As XmlNode
	XAttribute xTabIndex = default(XAttribute);
	
	//oControlNode = defXmlDoc.SelectSingleNode("//Controls/Control[@TableRow=" & row & "][@TableCol=" & col & "]")
	xControl = this.GetControlElement(xDoc, row, col);
	if (xControl != null)
	{
		//oTabIndexNode = oControlNode.SelectSingleNode("@TabIndex")
		xTabIndex = xControl.Attribute("TabIndex");
		if (xTabIndex == null)
		{
			xControl.Add(new XAttribute("TabIndex", tabIndex));
			//Utility.AddAttribute(defXmlDoc, oControlNode, "TabIndex", tabIndex)
		}
		else
		{
			xTabIndex.Value = tabIndex;
		}
	}
}

/// -----------------------------------------------------------------------------
/// <summary>
/// Get an Collection of FormControlInfo Objects for the Entire Form
/// </summary>
/// <param name="defXmlDoc">The Current Working Form XmlDocument</param>
/// <returns>ArryaList</returns>
/// <remarks>
/// The ArryaList contains all top-level Controls in the Form.
/// </remarks>
/// <history>
/// 	[steve]	4/30/2005	Created
/// </history>
/// -----------------------------------------------------------------------------

public List<FormControlInfo> GetFormControlArray(FormPageInfo page)
{
	
	return GetFormControlArray(XDocument.Parse(page.PageData));
	
}

public List<FormControlInfo> GetFormControlArray(XDocument xDoc)
{
	List<FormControlInfo> ControlsArray = new List<FormControlInfo>();
	FormControlInfo oFormControlInfo = default(FormControlInfo);
	
	IEnumerable<XElement> controls = xDoc.Elements("Form").Elements("Controls").Elements("Control");
	
	foreach (XElement control in controls)
	{
		oFormControlInfo = this.GetFormControlInfo(control);
		if (oFormControlInfo != null)
		{
			ControlsArray.Add(oFormControlInfo);
		}
	}
	
	return ControlsArray;
	
}

/// -----------------------------------------------------------------------------
/// <summary>
/// Returns the Name (Label) for the given Control
/// </summary>
/// <param name="defXmlDoc">The Current Working Form XmlDocument</param>
/// <param name="controlId">The ID of the form control</param>
/// <returns>String</returns>
/// <remarks>
/// </remarks>
/// <history>
/// 	[steve]	4/30/2005	Created
/// </history>
/// -----------------------------------------------------------------------------
public string GetControlNameById(XDocument xDoc, string controlId)
{
	string strControlName = "";
	//Dim oControlNode As XmlNode
	XElement xControl = default(XElement);
	//Dim oNode As XmlNode
	XAttribute xAttr = default(XAttribute);
	
	//oControlNode = defXmlDoc.SelectSingleNode("//Controls/Control[@ID='" & controlId & "']")
	xControl = this.GetControlElement(xDoc, controlId);
	if (xControl != null)
	{
		//oNode = oControlNode.SelectSingleNode("@FieldName")
		xAttr = xControl.Attribute("FieldName");
		
		if (xAttr == null)
		{
			//oNode = oControlNode.SelectSingleNode("@Label")
			xAttr = xControl.Attribute("Label");
		}
		
		if (xAttr != null)
		{
			strControlName = xAttr.Value;
		}
	}
	
	return strControlName;
	
}

public void ResetForm(XDocument xDoc)
{
	this.FormInfo.TableColumns = (byte) 1;
	this.FormInfo.TableRows = (byte) 1;
	this.FormInfo.ExtIdentityColumn = string.Empty;
	this.FormInfo.ExtTableConnStr = string.Empty;
	this.FormInfo.ExtTableName = string.Empty;
	this.FormInfo.UseExtTable = false;
	this.Update(this.FormInfo);
	xDoc.Descendants("Form").Elements("Controls").Elements("Control").Remove();
	this.Update(FormInfo);
	FormFieldRulesController objFieldRulesCtl = new FormFieldRulesController();
	objFieldRulesCtl.DeleteFormFieldRulesByForm(this._formInfo.FormID);
	FormMappingController objDataMapCtl = new FormMappingController();
	objDataMapCtl.Delete(this._formInfo.FormID);
}



#endregion

}

}


